// Mall/pages/mall/mall.js
const util = require('@utils/util1.js');
const api = require('@config/api.js');
const user = require('@utils/user.js');
//获取应用实例
var app = getApp();
let touchDotX = 0; //X按下时坐标
let touchDotY = 0; //y按下时坐标
let interval; //计时器
let time = 0; //从按下到松开共多少时间*100



Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 首页JS
    fenleiIndex: 0,
    SwitchTabSelected: 0,
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    Custom: app.globalData.Custom,
    hasLogin: false,
    Administrator: false,
    userInfo: {},
    banner: [],
    newGoods: [],
    hotGoods: [],
    allGoods: [],
    coupons: [],
    channel: [],
    rewardTaskList: [],
    grouponRuleList: [],
    page: 1,
    limit: 20,
    order: {
      unpaid: 0,
      unship: 0,
      unrecv: 0,
      uncomment: 0
    },

    // 底部导航栏列表
    list: [{
        name: "首页",
        img1: "/Mall/static/images/首页2.png",
        img2: "/Mall/static/images/首页1.png"
      },
      {
        name: "分类",
        img1: "/Mall/static/images/分类2.png",
        img2: "/Mall/static/images/分类1.png"
      },
      {
        name: "购物车",
        img1: "/Mall/static/images/购物车2.png",
        img2: "/Mall/static/images/购物车1.png"
      },
      {
        name: "我的",
        img1: "/Mall/static/images/我的2.png",
        img2: "/Mall/static/images/我的1.png"
      },

    ],
    totalPages: 1,
    swiperListA: [{
        url: "http://1.92.105.120/img/img1.png"
      },
      {
        url: "http://1.92.105.120/img/img1.png"
      },
      {
        url: "http://1.92.105.120/img/img1.png"
      }
    ],
    swiperListB: [{
        url: "http://1.92.105.120/img/img2.png"
      },
      {
        url: "http://1.92.105.120/img/img2.png"
      },
      {
        url: "http://1.92.105.120/img/img2.png"
      }
    ],


    //我的页面data
    hasLogin: false,
    Administrator: false,
    integralPrice: 0,
    userLevel: "普通用户",
    userInfo: {},
    brand: {},
    order: {
      unpaid: 0,
      unship: 0,
      unrecv: 0,
      uncomment: 0
    },

    // 分类data
    navList: [],
    goodsList: [],
    channel: [], // 你的分类数组
    fenleiIndex: 0, // 当前高亮下标
    rightCateIndex: 0, //右边高亮显示
    id: 0, // 当前分类 id
    navList: [], // 接口返回的兄弟分类列表
    currentCategory: {}, // 当前分类详情
    goodsList: [], // 要渲染的商品列表
    page: 1,
    limit: 10,
    scrollLeft: 0,
    currentCategory: {},
    scrollTop: 0,
    scrollHeight: 0,
    page: 1,
    limit: 10,

    // 购物车data
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    Custom: app.globalData.Custom,
    hasLogin: false,
    Administrator: false,
    userInfo: {},
    goods: {},
    cartGoods: [],
    cartTotal: {
      "goodsCount": 0,
      "goodsAmount": 0.00,
      "checkedGoodsCount": 0,
      "checkedGoodsAmount": 0.00
    },
    isEditCart: false,
    checkedAllStatus: true,
    editCartList: [],
    openAttr: false, //规格打开判断
    checkedSpecText: '请选择规格数量',
    goodsIndex: 0,
    tmpSpecText: "请选择规格数量",
    checkedSpecPrice: 0, //规格价格
    checkedNumber: 0, //规格商品数量
    productList: [],
    specificationList: [], //规格列表
    checkedSpecPicUrl: '', //规格默认图片

  },

  // 分类js


  getCategoryInfo (e) {
    const newId = e.currentTarget.dataset.id;
    const newIndex = e.currentTarget.dataset.index;

    this.setData({
      fenleiIndex: newIndex,
      id: newId,
      goodsList: [],
      page: 1
    });

    // 获取一级分类对应的兄弟分类（即二级菜单）
    util.request(api.GoodsCategory, {
        id: newId
      })
      .then(res => {
        if (res.errno === 'success') {
          const brotherCategory = res.data.brotherCategory || [];
          const firstSubCategory = brotherCategory[0] || {};

          this.setData({
            navList: brotherCategory,
            currentCategory: firstSubCategory,
            scrollLeft: 0
          });

          wx.setNavigationBarTitle({
            title: res.data.parentCategory.name
          });

          this.getGoodsList(); // 拉第一个二级分类的商品
        } else {
          wx.showToast({
            title: '加载分类失败：' + (res.errmsg || ''),
            icon: 'none'
          });
        }
      })
      .catch(() => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      });
  },

  // 拉商品方法
  getGoodsList: function () {
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    util.request(api.GoodsList, {
      categoryId: this.data.currentCategory.id,
      page: this.data.page,
      limit: this.data.limit
    }).then(res => {
      wx.hideLoading();
      if (res.errno === 'success') {
        this.setData({
          goodsList: this.data.goodsList.concat(res.data.list),
          totalPages: res.data.pages
        });
      }
    }).catch(() => {
      wx.hideLoading();
      wx.showToast({
        title: '拉取商品失败',
        icon: 'none'
      });
    });
  },
  switchCate: function (e) {
    const newId = e.currentTarget.dataset.id;
    const newIndex = e.currentTarget.dataset.index;

    // 如果点击同一个分类不处理
    if (newId === this.data.currentCategory.id) return;

    this.setData({
      // fenleiIndex: newIndex,
      rightCateIndex: newIndex,  
      id: newId,
      goodsList: [],
      page: 1,
      currentCategory: {
        id: newId
      } // 只更新当前分类 ID
    });

    this.getGoodsList();
  },


  home() {
    wx.navigateBack()
  },
  // 底部导航栏点击事件
  switchTab(e) {
    const index = e.currentTarget.dataset.index;
    console.log(index);
    this.setData({
      SwitchTabSelected: index
    });
  },
  // 购物车JS

  getCartList: function () {
    console.log()
    if (!app.globalData.hasLogin) {
      return;
    }
    wx.showLoading({
      title: '加载中...',
      mask: true,
      duration: 3000
    });
    let that = this;
    util.request(api.CartList).then(function (res) {
      if (res.errno === "success") {
        that.setData({
          cartGoods: res.data.cartList,
          cartTotal: res.data.cartTotal
        });
        that.setData({
          checkedAllStatus: that.isCheckedAll()
        });
        wx.hideLoading();
      }
    });
  },

  //关闭规格弹窗
  closeAttr: function () {
    this.setData({
      openAttr: false,
    });
  },

  //规格选择弹出
  switchAttrPop: function (event) {
    let that = this;
    if (this.data.openAttr == false) {
      let itemIndex = event.target.dataset.itemIndex;
      let cartItem = that.data.cartGoods[itemIndex];
      util.request(api.GoodsDetail, {
        goodId: cartItem.goodsId
      }).then(function (res) {
        if (res.errno === "success") {
          let _specificationList = res.data.specificationList;
          for (var i = 0; i < _specificationList.length; i++) {
            for (var j = 0; j < _specificationList[i].valueList.length; j++) {
              if (cartItem.specifications == _specificationList[i].valueList[j].value) {
                _specificationList[i].valueList[j].checked = true
              }
            }
          }
          that.setData({
            openAttr: !that.data.openAttr,
            goods: res.data.info,
            productList: res.data.productList,
            checkedNumber: cartItem.number,
            checkedSpecPrice: cartItem.price,
            checkedSpecPicUrl: cartItem.picUrl,
            specificationList: res.data.specificationList,
            checkedSpecText: cartItem.specifications,
            tmpSpecText: cartItem.specifications,
            goodsIndex: itemIndex,
          });
        }
      });
    }
  },

  // 规格选择
  clickSkuValue: function (event) {
    let specName = event.currentTarget.dataset.name;
    let specValueId = event.currentTarget.dataset.valueId;
    //判断是否可以点击

    //TODO 性能优化，可在wx:for中添加index，可以直接获取点击的属性名和属性值，不用循环
    let _specificationList = this.data.specificationList;
    for (let i = 0; i < _specificationList.length; i++) {
      if (_specificationList[i].name === specName) {
        for (let j = 0; j < _specificationList[i].valueList.length; j++) {
          if (_specificationList[i].valueList[j].id == specValueId) {
            //如果已经选中，则反选
            if (_specificationList[i].valueList[j].checked) {
              _specificationList[i].valueList[j].checked = false;
            } else {
              _specificationList[i].valueList[j].checked = true;
            }
          } else {
            _specificationList[i].valueList[j].checked = false;
          }
        }
      }
    }

    this.setData({
      specificationList: _specificationList,
    });
    //重新计算spec改变后的信息
    this.changeSpecInfo();
    //重新计算哪些值不可以点击
  },

  //获取选中的团购信息
  getCheckedGrouponValue: function () {
    let checkedValues = {};
    let _grouponList = this.data.groupon;
    for (let i = 0; i < _grouponList.length; i++) {
      if (_grouponList[i].checked) {
        checkedValues = _grouponList[i];
      }
    }
    return checkedValues;
  },

  //获取选中的规格信息
  getCheckedSpecValue: function () {
    let checkedValues = [];
    let _specificationList = this.data.specificationList;
    for (let i = 0; i < _specificationList.length; i++) {
      let _checkedObj = {
        name: _specificationList[i].name,
        valueId: 0,
        valueText: '',
      };
      for (let j = 0; j < _specificationList[i].valueList.length; j++) {
        if (_specificationList[i].valueList[j].checked) {
          _checkedObj.valueId = _specificationList[i].valueList[j].id;
          _checkedObj.valueText = _specificationList[i].valueList[j].value;
        }
      }
      checkedValues.push(_checkedObj);
    }
    return checkedValues;
  },

  //判断规格是否选择完整
  isCheckedAllSpec: function () {
    return !this.getCheckedSpecValue().some(function (v) {
      if (v.valueId == 0) {
        return true;
      }
    });
  },

  getCheckedSpecKey: function () {
    let checkedValue = this.getCheckedSpecValue().map(function (v) {
      return v.valueText;
    });
    return checkedValue;
  },

  // 规格改变时，重新计算价格及显示信息
  changeSpecInfo: function () {
    let checkedNameValue = this.getCheckedSpecValue();
    //设置选择的信息
    let checkedValue = checkedNameValue.filter(function (v) {
      if (v.valueId != 0) {
        return true;
      } else {
        return false;
      }
    }).map(function (v) {
      return v.valueText;
    });
    if (checkedValue.length > 0) {
      this.setData({
        tmpSpecText: checkedValue.join(' ')
      });
    } else {
      this.setData({
        tmpSpecText: '请选择规格数量'
      });
    }
    if (this.isCheckedAllSpec()) {
      this.setData({
        checkedSpecText: this.data.tmpSpecText
      });
      // 规格所对应的货品选择以后
      let checkedProductArray = this.getCheckedProductItem(this.getCheckedSpecKey());
      if (!checkedProductArray || checkedProductArray.length <= 0) {
        this.setData({
          soldout: true,
        });
        console.error('规格所对应货品不存在');
        return;
      }
      let checkedProduct = checkedProductArray[0];
      if (checkedProduct.number > 0) {
        this.setData({
          checkedSpecPrice: checkedProduct.price,
          checkedSpecPicUrl: checkedProduct.url,
          soldout: false
        });
      } else {
        this.setData({
          checkedSpecPrice: this.data.goods.retailPrice,
          soldout: true
        });
      }
    } else {
      this.setData({
        checkedSpecText: '规格数量选择',
        checkedSpecPrice: this.data.goods.retailPrice,
        soldout: false
      });
    }
  },

  // 获取选中的产品（根据规格）
  getCheckedProductItem: function (key) {
    return this.data.productList.filter(function (v) {
      if (v.specifications.toString() == key.toString()) {
        return true;
      } else {
        return false;
      }
    });
  },

  isCheckedAll: function () {
    //判断购物车商品已全选
    return this.data.cartGoods.every(function (element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });
  },

  doCheckedAll: function () {
    this.setData({
      checkedAllStatus: this.isCheckedAll()
    });
  },

  checkedItem: function (event) {
    let itemIndex = event.target.dataset.itemIndex;
    let that = this;
    let productIds = [];
    productIds.push(that.data.cartGoods[itemIndex].productId);
    if (!this.data.isEditCart) {
      util.request(api.CartChecked, {
        productIds: productIds,
        isChecked: that.data.cartGoods[itemIndex].checked ? 0 : 1
      }, 'POST').then(function (res) {
        if (res.errno === "success") {
          that.setData({
            cartGoods: res.data.cartList,
            cartTotal: res.data.cartTotal
          });
        }
        that.setData({
          checkedAllStatus: that.isCheckedAll()
        });
      });
    } else {
      //编辑状态
      let tmpCartData = this.data.cartGoods.map(function (element, index, array) {
        if (index == itemIndex) {
          element.checked = !element.checked;
        }
        return element;
      });
      that.setData({
        cartGoods: tmpCartData,
        checkedAllStatus: that.isCheckedAll(),
        'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount()
      });
    }
  },

  getCheckedGoodsCount: function () {
    let checkedGoodsCount = 0;
    this.data.cartGoods.forEach(function (v) {
      if (v.checked === true) {
        checkedGoodsCount += v.number;
      }
    });
    return checkedGoodsCount;
  },

  checkedAll: function () {
    let that = this;
    if (!this.data.isEditCart) {
      var productIds = this.data.cartGoods.map(function (v) {
        return v.productId;
      });
      util.request(api.CartChecked, {
        productIds: productIds,
        isChecked: that.isCheckedAll() ? 0 : 1
      }, 'POST').then(function (res) {
        if (res.errno === "success") {
          that.setData({
            cartGoods: res.data.cartList,
            cartTotal: res.data.cartTotal
          });
        }
        that.setData({
          checkedAllStatus: that.isCheckedAll()
        });
      });
    } else {
      //编辑状态
      let checkedAllStatus = that.isCheckedAll();
      let tmpCartData = this.data.cartGoods.map(function (v) {
        v.checked = !checkedAllStatus;
        return v;
      });
      that.setData({
        cartGoods: tmpCartData,
        checkedAllStatus: that.isCheckedAll(),
        'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount()
      });
    }

  },

  editCart: function () {
    var that = this;
    if (this.data.isEditCart) {
      this.getCartList();
      this.setData({
        isEditCart: !this.data.isEditCart
      });
    } else {
      //编辑状态
      let tmpCartList = this.data.cartGoods.map(function (v) {
        v.checked = false;
        return v;
      });
      this.setData({
        editCartList: this.data.cartGoods,
        cartGoods: tmpCartList,
        isEditCart: !this.data.isEditCart,
        checkedAllStatus: that.isCheckedAll(),
        'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount()
      });
    }
  },

  submitAttr: function (event) {
    let that = this;
    if (that.isCheckedAllSpec()) {
      let itemIndex = event.target.dataset.itemIndex;
      let cartItem = that.data.cartGoods[itemIndex];
      cartItem.number = that.data.checkedNumber;
      //根据选中的规格，判断是否有对应的sku信息
      let checkedProductArray = this.getCheckedProductItem(this.getCheckedSpecKey());
      if (!checkedProductArray || checkedProductArray.length <= 0) {
        //找不到对应的product信息，提示没有库存
        util.showErrorModal('没有库存');
        return false;
      }
      let checkedProduct = checkedProductArray[0];
      //验证库存
      if (checkedProduct.number <= 0) {
        util.showErrorModal('没有库存');
        return false;
      }
      that.updateCart(checkedProduct.id, cartItem.goodsId, cartItem.number, cartItem.id);
      cartItem.price = checkedProduct.price;
      cartItem.specifications = checkedProduct.specifications;
      cartItem.picUrl = checkedProduct.url;
      //关闭规格
      that.closeAttr();
    } else {
      util.showErrorModal("请选择完整规格");
    }
  },

  updateCart: function (productId, goodsId, number, id) {
    let that = this;
    util.request(api.CartUpdate, {
      productId: productId,
      goodsId: goodsId,
      number: number,
      id: id
    }, 'POST').then(function (res) {
      if (res.errno === "success") {
        that.setData({
          checkedAllStatus: that.isCheckedAll(),
          cartGoods: that.data.cartGoods,
          checkedNumber: number
        });
      }
    });
  },

  cutNumber: function (event) {
    let that = this;
    let itemIndex = event.target.dataset.itemIndex;
    let cartItem = that.data.cartGoods[itemIndex];
    let number = (cartItem.number - 1 > 1) ? cartItem.number - 1 : 1;
    that.updateCart(cartItem.productId, cartItem.goodsId, number, cartItem.id);
    cartItem.number = number;
    var productIds = this.data.cartGoods.map(function (v) {
      return v.productId;
    });
    util.request(api.CartChecked, {
      productIds: productIds,
      isChecked: 1
    }, 'POST').then(function (res) {
      if (res.errno === "success") {
        that.setData({
          cartGoods: res.data.cartList,
          cartTotal: res.data.cartTotal
        });
      }
    });
  },

  addNumber: function (event) {
    let that = this;
    let itemIndex = event.target.dataset.itemIndex;
    let cartItem = that.data.cartGoods[itemIndex];
    let number = cartItem.number + 1;
    that.updateCart(cartItem.productId, cartItem.goodsId, number, cartItem.id);
    cartItem.number = number;
    var productIds = this.data.cartGoods.map(function (v) {
      return v.productId;
    });
    util.request(api.CartChecked, {
      productIds: productIds,
      isChecked: 1
    }, 'POST').then(function (res) {
      if (res.errno === "success") {
        that.setData({
          cartGoods: res.data.cartList,
          cartTotal: res.data.cartTotal
        });
      }
    });
  },

  checkoutOrder: function () {
    //获取已选择的商品
    let that = this;
    var checkedGoods = this.data.cartGoods.filter(function (element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });
    if (checkedGoods.length <= 0) {
      return false;
    }
    // storage中设置了cartId，则是购物车购买
    try {
      wx.setStorageSync('cartId', 0);
      wx.navigateTo({
        url: '../checkout/checkout'
      })
    } catch (e) {}

  },

  deleteCart: function () {
    //获取已选择的商品
    let that = this;
    let productIds = this.data.cartGoods.filter(function (element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });
    if (productIds.length <= 0) {
      return false;
    }
    productIds = productIds.map(function (element, index, array) {
      if (element.checked == true) {
        return element.productId;
      }
    });
    util.request(api.CartDelete, {
      productIds: productIds
    }, 'POST').then(function (res) {
      if (res.errno === "success") {
        let cartList = res.data.cartList.map(v => {
          v.checked = false;
          return v;
        });
        that.setData({
          cartGoods: cartList,
          cartTotal: res.data.cartTotal
        });
      }
      that.setData({
        checkedAllStatus: that.isCheckedAll()
      });
    });
  },

  goLogin() {
    wx.navigateTo({
      url: "/Mall/pages/login/login"
    });
  },

  // 我的页面JS
  getProfile() {
    util.navigate("/pages/ucenter/profile/profile");
  },
  goQrAuth() {
    util.navigate("/pages/auth/qrauth/qrauth");
  },
  goLogin() {

    wx.navigateTo({
      url: '/Mall/pages/login/login'
    });
    if (!this.data.hasLogin) {
      util.navigate("/Mall/pages/login/login");
    }
  },
  goOrder() {
    if (this.data.hasLogin) {
      util.navigate("/pages/ucenter/order/order?tab=0");
    } else {
      util.navigate("/pages/auth/login/login");
    }
  },
  shareMe() {
    if (this.data.hasLogin) {
      util.navigate("/pages/ucenter/shareMe/shareMe");
    } else {
      util.navigate("/pages/auth/login/login");
    }
  },
  goWithdraw() {
    if (this.data.hasLogin) {
      util.navigate("/pages/ucenter/withdraw/withdraw");
    } else {
      util.navigate("/pages/auth/login/login");
    }
  },
  goOrderIndex(e) {
    if (this.data.hasLogin) {
      let tab = e.currentTarget.dataset.index
      let route = e.currentTarget.dataset.route
      util.navigate(route + '?tab=' + tab);
    } else {
      util.navigate("/pages/auth/login/login");
    };
  },
  goBrand() {
    let that = this;
    let brand = that.data.brand;
    if (!that.data.hasLogin) {
      util.navigate("/pages/auth/login/login");
      return;
    }
    if (!brand) {
      util.navigate("/pages/brand/brandAdd/brandAdd");
      return;
    }
    util.navigate("/pages/brand/brandDetail/brandDetail?id=" + brand.id + "&status=1");
  },
  goDaily() {
    util.navigate("/pages/issue/issueDaily/issueDaily");
  },
  goCoupon() {
    util.navigate("/pages/ucenter/couponList/couponList");
  },
  goCollect() {
    util.navigate("/pages/ucenter/collect/collect");
  },
  goFeedback(e) {
    util.navigate("/pages/ucenter/feedback/feedback");
  },
  goFootprint() {
    util.navigate("/pages/ucenter/footprint/footprint");
  },
  goAddress() {
    util.navigate("/Mall/pages/address/address");
  },
  goAfterSale: function () {
    util.navigate("/pages/ucenter/aftersaleList/aftersaleList");
  },
  aboutUs: function () {
    util.navigate("/pages/ucenter/about/about");
  },
  goHelp: function () {
    util.navigate("/pages/ucenter/help/help");
  },

  bindPhoneNumber: function (e) {
    if (e.detail.errMsg !== "getPhoneNumber:ok") {
      // 拒绝授权
      return;
    }
    if (!this.data.hasLogin) {
      wx.showToast({
        title: '绑定失败：请先登录',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    util.request(api.AuthBindPhone, {
      iv: e.detail.iv,
      encryptedData: e.detail.encryptedData
    }, 'POST').then(function (res) {
      if (res.errno === "success") {
        wx.showToast({
          title: '绑定手机号码成功',
          icon: 'success',
          duration: 2000
        });
      }
    });
  },

  exitLogin: function () {
    wx.showModal({
      title: '退出登录',
      confirmColor: '#b4282d',
      content: '确认退出登录？',
      success: function (res) {
        if (!res.confirm) {
          return;
        }
        util.request(api.AuthLogout, {}, 'POST');
        app.globalData.hasLogin = false;
        app.globalData.Administrator = false;
        //清除用户数据
        wx.removeStorageSync('userToken');
        wx.removeStorageSync('userInfo');
        //清除管理员数据
        wx.removeStorageSync('adminInfo');
        wx.removeStorageSync('adminToken');
        wx.reLaunch({
          url: '/pages/index/index'
        });
      }
    })
  },

  // 触摸开始事件，滑动打开关闭抽屉
  touchStart: function (e) {
    touchDotX = e.touches[0].pageX; // 获取触摸时的原点
    touchDotY = e.touches[0].pageY;
    // 使用js计时器记录时间    
    interval = setInterval(function () {
      time++;
    }, 100);
  },
  // 触摸结束事件，滑动打开关闭抽屉
  touchEnd: function (e) {
    let touchMoveX = e.changedTouches[0].pageX;
    let touchMoveY = e.changedTouches[0].pageY;
    let tmX = touchMoveX - touchDotX;
    let tmY = touchMoveY - touchDotY;
    if (time < 20 && (tmX > 200 || tmX < -50)) {
      let absX = Math.abs(tmX);
      let absY = Math.abs(tmY);
      if (absX > 2 * absY) {
        if (tmX < 0) {
          this.setData({
            modalName: null
          })
        } else {
          this.setData({
            modalName: "viewModal"
          })
        }
      }
    }
    clearInterval(interval); // 清除setInterval
    time = 0;
  },


  //打开抽屉
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },

  //关闭抽屉
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },


  // 首页JS

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    wx.reLaunch({
      url: '/pages/home/home'
    });
  },

  wodedingdan() {
    wx.navigateTo({
      url: '/Mall/pages/order/order?tab=0',
    })
  },
  addressJump() {
    wx.navigateTo({
      url: '/Mall/pages/address/address',
    })
  },

  goOrderIndex(e) {
    if (this.data.hasLogin) {
      let tab = e.currentTarget.dataset.index
      let route = e.currentTarget.dataset.route
      util.navigate(route + '?tab=' + tab);
    } else {
      util.navigate("/pages/auth/login/login");
    };
  },
  // switchCate: function (event) {
  //   const id = event.currentTarget.dataset.id;
  //   const index = event.currentTarget.dataset.index;

  //   this.setData({
  //     fenleiIndex: index
  //   });
  //   console.log(id);
  // },

  getGrouponGoods(res) {
    console.log(res.currentTarget.dataset.id);
    let id = res.currentTarget.dataset.id;
    util.navigate("/Mall/pages/goodsDetail/goodsDetail?goodId=" + id)
  },

  /**
   * 添加赏金分享
   * @param {} e 
   */
  rewardShare: function (e) {
    let rewardTaskId = e.currentTarget.dataset.id
    util.request(api.RewardCreate, {
      rewardTaskId: rewardTaskId
    }, "POST").then(function (res) {
      if (res.errno === "success") {
        util.navigate("/Mall/pages/goodsDetail/goodsDetail?rewardId=" + res.data.id);
      }
    });
  },

  getIndexData: function () {
    wx.showLoading({
      title: '加载中...',
      mask: true,
      duration: 3000
    });
  
    let that = this;
    util.request(api.IndexUrl, {
      appid: util.getAppid()
    }).then(function (res) {
      console.log(res);
      wx.hideLoading();
  
      if (res.errno === "success") {
        that.clearIndexData();
        wx.setStorageSync('tenantId', res.data.tenantId);
  
        that.setData({
          banner: res.data.banner,
          newGoods: res.data.newGoodsList,
          hotGoods: res.data.hotGoodsList,
          rewardTaskList: res.data.rewardTaskList,
          grouponRuleList: res.data.grouponRuleList,
          allGoods: res.data.allGoodsList.list,
          totalPages: res.data.allGoodsList.pages,
          coupons: res.data.couponList,
          channel: res.data.channel
        });
  
        if (res.data.channel && res.data.channel.length > 0) {
          const defaultCate = res.data.channel[0];
          const defaultId = defaultCate.id;
  
          that.setData({
            fenleiIndex: 0,
            id: defaultId
          });
  
          that.getCategoryInfo({
            currentTarget: {
              dataset: {
                id: defaultId,
                index: 0
              }
            }
          });
        }
      }
    });
  },
  
  clearIndexData: function () {
    let that = this;
    that.setData({
      page: 1,
    });
  },

  /**分页获取商品 */
  getGoodsAll: function () {
    wx.showLoading({
      title: '加载中...',
      mask: true,
      duration: 3000
    });
    let that = this;
    util.request(api.GoodsList, {
      page: that.data.page,
      limit: that.data.limit
    }).then(function (res) {
      wx.hideLoading();
      if (res.errno === "success") {
        that.setData({
          allGoods: that.data.allGoods.concat(res.data.list),
          totalPages: res.data.pages,
        });
      }
    });
  },

  //如果有可领优惠券则打开弹窗
  showCoupon(e) {
    this.redPacket.openTheCouponPopUp();
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this;
    //轮播商品获取宽高度
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          windowWidth: res.windowWidth,
          windowHeight: res.windowHeight
        });
      }
    });

    let sceneId, sceneType;
    //页面初始化海报分享扫码
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      let info_arr = scene.split(',');
      sceneType = info_arr[0];
      sceneId = info_arr[1];
    }

    //存储分享者用户信息
    if (sceneType == "inviter") {
      wx.setStorageSync('inviter', sceneId);
    }

    if (options.inviter) {
      wx.setStorageSync('inviter', options.inviter);
    }

    console.log("inviter", wx.getStorageSync('inviter'))

    // 页面初始化朋友圈分享
    if (options.goodsId) {
      sceneId = options.goodsId;
      sceneType = "goodsId";
    }
    if (options.grouponId) {
      sceneId = options.grouponId;
      sceneType = "grouponId";
    }
    if (options.rewardId) {
      sceneId = options.rewardId;
      sceneType = "rewardId";
    }


    //判断首页初始化参数是否正常
    if (sceneType == 'goodsId' || sceneType == 'grouponId' || sceneType == 'rewardId') {
      util.request(api.NavigateUrl, {
        sceneId: sceneId,
        sceneType: sceneType,
      }, 'POST').then(function (res) {
        if (res.errno === "success") {
          if (sceneType == 'goodsId') {
            util.navigate("/Mall/pages/goodsDetail/goodsDetail?goodId=" + sceneId);
          }
          if (sceneType == 'grouponId') {
            util.navigate("/Mall/pages/goodsDetail/goodsDetail?grouponId=" + sceneId);
          }
          if (sceneType == 'rewardId') {
            util.navigate("/Mall/pages/goodsDetail/goodsDetail?rewardId=" + sceneId);
          }
        }
      });
    }
    //加载优惠券组件
    this.redPacket = this.selectComponent("#redPacket");

    //加载首页数据
    this.getIndexData();
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    //获取用户的登录信息
    if (app.globalData.hasLogin) {
      let userInfo = wx.getStorageSync('userInfo');
      this.setData({
        userInfo: userInfo,
        hasLogin: true
      });
      //管理员登录
      if (app.globalData.Administrator) {
        this.setData({
          Administrator: true
        });
      }
    }

    //自定义底部导航栏高亮显示不加会导致高亮随机跳
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
    }
    if (app.globalData.hasLogin) {
      let userInfo = wx.getStorageSync('userInfo');
      this.setData({
        userInfo: userInfo,
        hasLogin: true
      });
      //管理员登录
      if (app.globalData.Administrator) {
        this.setData({
          Administrator: true
        });
      }
      let that = this;
      util.request(api.UserIndex).then(function (res) {
        if (res.errno === "success") {
          that.setData({
            order: res.data.order,
            brand: res.data.brand,
            userLevel: res.data.userLevel,
            integralPrice: res.data.integralPrice
          });
        }
      });
      this.getCartList();
    }

    //自定义底部导航栏高亮显示不加会导致高亮随机跳
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 4
      })
    }
  },
  gotocart(e) {
    util.navigate("/Mall/pages/cart/cart");
  },
  gotopersonal(e) {
    wx.navigateTo({
      url: '/Mall/pages/personal/personal',
    })
  },
  gotoclassification(e) {
    wx.navigateTo({
      url: '/Mall/pages/classification/classification',
    })
  },
  gotomy(e) {
    wx.navigateTo({
      url: '/Mall/pages/my/my',
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.getIndexData();
    this.getCartList();
    //在当前页面显示导航条加载动画
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新






  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    let that = this;
    if (that.data.totalPages > that.data.page) {
      that.setData({
        page: that.data.page + 1
      });
      that.getGoodsAll();
    } else {
      wx.showToast({
        title: '没有更多信息了',
        icon: 'none',
        duration: 2000
      });
      return false;
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: 'litemall-plus-wx',
      desc: '唯爱与生活不可辜负',
      path: '/pages/index/index'
    }
  },


  goAfterSale: function () {
    util.navigate("/Mall/pages/aftersaleList/aftersaleList");
  },
  goOrderIndex(e) {
    if (this.data.hasLogin) {
      let tab = e.currentTarget.dataset.index
      let route = e.currentTarget.dataset.route
      util.navigate(route + '?tab=' + tab);
    } else {
      util.navigate("/Mall/pages/login/login");
    };
  },

  // 跳转 订单管理、购物车、地址管理、我的
  Jump(e) {
    console.log(e.currentTarget.dataset.index)
    const index = e.currentTarget.dataset.index
    if (index === 0) {
      util.navigate("../ucenter/order/order");


    }
  }

})